package code.jzh.compiler.scanner;

import java.util.HashMap;
import java.util.Map;

public class Lexer {
	public static Map<String, MinimalDFA> dfaMap = new HashMap<String, MinimalDFA>();
	
	static {
		for(LexerType lType : LexerType.values()) {
			MinimalDFA minimalDFA = buildMinimalDFA(lType.pattern);
			dfaMap.put(lType.toString(), minimalDFA);
		}
	}
	
	public static MinimalDFA buildMinimalDFA(String regularStr) {
		regularStr = RegularExpression.formatRegularExpression(regularStr);
		NFA nfa = NFA.buildNFA(regularStr);
		DFA dfa = DFA.buildDFA(nfa);
		MinimalDFA minimalDFA = MinimalDFA.buildMinimalDFA(dfa);
		return minimalDFA;
	}
	
	public static void process(String code) throws Exception {
		while(code!=null && code.length()!=0)
			code = processWord(code);
	}
	
	public static String processWord(String code) throws Exception {
		Lexeme lexeme = null;
		for(LexerType lType : LexerType.values()) {
			MinimalDFA dfa = dfaMap.get(lType.toString());
			int walk_end = 0, accepted_end = 0;
			MinimalDFAState currState = dfa.start;
			boolean accepted = false;
			while(walk_end<code.length()) {
				char c = code.charAt(walk_end);
				currState = dfa.move(currState, c);
				if(currState==null) {
					break;
				}else {
					if(currState.accepted) {
						accepted = true;
						accepted_end = walk_end;
					}
				}
				walk_end++;
			}
			if(accepted) {
				if(lexeme==null || walk_end>lexeme.literal.length())//lexeme为空（第一次） 或者新的比老的长度长 才赋值
					//否则void会被归为identifier
					lexeme = new Lexeme(lType.ordinal(), code.substring(0, accepted_end+1), lType.toString());
			}
		}
		if(lexeme!=null) {
			lexeme.printLexeme();
			return code.substring(lexeme.literal.length());
		}
		return null;
	}
}
